package yams.domain;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.*;
import org.springframework.util.CollectionUtils;
import yams.common.constants.ContractStatusEnum;
import yams.common.constants.HouseGroupEnum;
import yams.common.constants.HouseStatusEnum;
import yams.common.constants.ShortRentTypeEnum;
import yams.repository.IEnumRepository;
import yams.utils.BeanUtil;
import yams.utils.ContextUtil;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * 公寓出租的最小单位
 * Created by Silence on 2016/10/11.
 */
@Entity(name = "T_HOUSE")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties({"userReserveds", "dayPrices","checkmeters","contracts"})
public class HouseEntity extends AbstractEntity {

    /**
     * 图片，简单描述，地址，房屋类型 , 房间号 , 管家ID , 负责人
     */
    String primaryImage, shortDesc, address, houseType , houseNumber, manager,account;
    /**
     *  房屋照片
     */
    String aImage, bImage, cImage, dImage, eImage, fImage;
    String gImage, hImage, iImage, jImage, kImage, lImage;
    /**
     * 推荐房源
     */
    Boolean recommend = false;
    /**
     * 可日租
     */
    Boolean dayRentAble = false;
    /**
     * 可月租
     */
    Boolean monthRentAble = false;
    /**
     * 可否加床
     */
    Boolean addBedAble = false;
    /**
     * 楼层
     */
    Long floor = 0L;
    /**
     * 面积，月租金,物业费
     */
    Double area, monthly,propertyFee;

    /**
     * 房型组
     */
    String houseGroup;

    @Lob
    @Column(length = 20971520)
    String uedit;

    @OneToMany(mappedBy = "house", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @OrderBy(value = "modifiedDate DESC")
    Set<ContractEntity> contracts;

    @ManyToOne(cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    @JoinColumn(name = "APART_ID")
    ApartmentEntity apartment;

    @OneToMany(mappedBy = "house", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @OrderBy(value = "rowNum DESC")
    Set<SkuEntity> products;

    @OneToMany(mappedBy = "house", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @OrderBy(value = "modifiedDate DESC")
    Set<UserReserved> userReserveds;

    @OneToMany(mappedBy = "house", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @OrderBy(value = "rowNum DESC")
    Set<BedEntity> beds;

    @OneToMany(mappedBy = "house", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @OrderBy(value = "rowNum DESC")
    Set<DayPriceEntity> dayPrices;

    @OneToMany(mappedBy = "house", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @OrderBy(value = "rowNum DESC")
    Set<CheckmeterEntity> checkmeters;

    /**
     * 不管是预订，还是入住，此房的最早开始时间，和结束时间
     * 1. 如果房屋是预订状态，则为预订开始时间
     * 2. 如果房屋是入住状态，则为入住的开始时间
     */
    Date startDate, endDate;

    @Transient
    Map<String,BigDecimal> shortPrices;

    @Transient
    String apartmentCity;

    public String getHouseGroupName(){
        for (HouseGroupEnum anEnum : HouseGroupEnum.values()) {
            if (Objects.equals(anEnum.getValue(), this.houseGroup)) {
                return anEnum.getText();
            }
        }
        return houseGroup + "";

    }

    public String getStatusName() {
        for (HouseStatusEnum anEnum : HouseStatusEnum.values()) {
            if (Objects.equals(anEnum.getValue(), this.status)) {
                return anEnum.getText();
            }
        }
        return status + "";
    }

    public String getPrimaryImage() {
        return aImage;
    }

    public String getHouseTypeName() {
        IEnumRepository enumRepository = ContextUtil.getBean("enumRepository", IEnumRepository.class);
        EnumEntity enumEntity = enumRepository.findByCode("houseType");
        for (EnumItemEntity itemEntity : enumEntity.getItems()) {
            if (this.getHouseType() != null && this.getHouseType().equals(itemEntity.getCode()))
                return itemEntity.getName();
        }
        return this.getHouseType();
    }

    public String getApartmentId() {
        if (this.getApartment() != null)
            return this.getApartment().getId();
        return "";
    }
    public String getApartmentName() {
        if (this.getApartment() != null)
            return this.getApartment().getName();
        return "";
    }
    public String getApartmentCity() {
        if (this.getApartment() != null)
            return this.getApartment().getCity();
        return "";
    }

    public String getMyAddress() {
        if (this.getAddress() != null)
            return this.getAddress();
        if (this.getApartment() != null)
            return this.getApartment().getAddress();
        return "";
    }

    public Set<BedEntity> findBeds() {
        Set<BedEntity> result = Sets.newConcurrentHashSet();
        if (this.getBeds() != null){
            this.getBeds().forEach(item -> {
                BedEntity bed = new BedEntity();
                bed.setId(item.getId());
                bed.setCode(item.getCode());
                bed.setBedLength(item.getBedLength());
                bed.setBedType(item.getBedType());
                bed.setBedWidth(item.getBedWidth());
                result.add(bed);

            });
            return result;
        }
        return null;
    }

    public Set<DayPriceEntity> findDayPrices() {
        Set<DayPriceEntity> result = Sets.newConcurrentHashSet();
        if (this.getDayPrices() != null){
            this.getDayPrices().forEach(item -> {
                DayPriceEntity price = new DayPriceEntity();
                price.setId(item.getId());
                price.setCode(item.getCode());
                price.setShortRentType(item.getShortRentType());
                price.setDayPrice(item.getDayPrice());
                result.add(price);

            });
            return result;
        }
        return null;
    }
    /**
     * 获取房间日租价格
     * @return
     */
    public Map<String,BigDecimal> getShortPrices(){
        Map<String,BigDecimal> resultMap = Maps.newConcurrentMap();
        if (this.getDayPrices() != null){
            for(DayPriceEntity item : this.getDayPrices()){
                if(Objects.equals(ShortRentTypeEnum.SRT03.getValue(),item.getShortRentType())){
                    resultMap.put(ShortRentTypeEnum.SRT03.getValue(),item.getDayPrice());
                }else if(Objects.equals(ShortRentTypeEnum.SRT05.getValue(),item.getShortRentType())){
                    resultMap.put(ShortRentTypeEnum.SRT05.getValue(),item.getDayPrice());
                }else if(Objects.equals(ShortRentTypeEnum.SRT08.getValue(),item.getShortRentType())){
                    resultMap.put(ShortRentTypeEnum.SRT08.getValue(),item.getDayPrice());
                }else if(Objects.equals(ShortRentTypeEnum.SRT24.getValue(),item.getShortRentType())){
                    resultMap.put(ShortRentTypeEnum.SRT24.getValue(),item.getDayPrice());
                }
            }
        }
        return resultMap;
    }

    /* house实体直接关联其它的表 start */
    public Set<SkuEntity> getProducts() {
        Set<SkuEntity> skuSet = Sets.newHashSet();
        if(!CollectionUtils.isEmpty(this.products)){
            for(SkuEntity sku : this.products){
                SkuEntity skuEntity = new SkuEntity();
                BeanUtil.beanCopy(sku, skuEntity, "product","house");
                skuSet.add(skuEntity);
            }
        }
        return skuSet;
    }
    public ContractEntity getContract() {
        ContractEntity result = null;
        if(!CollectionUtils.isEmpty(this.contracts)){
            for(ContractEntity contract : this.contracts){
                if(Objects.equals(ContractStatusEnum.EXECUTING.getValue(),contract.getStatus())){
                    ContractEntity contractEntity = new ContractEntity();
                    BeanUtil.beanCopy(contract, contractEntity, "house");
                    result = contractEntity;
                }
            }
        }
        return result;
    }
    public ApartmentEntity getApartment() {
        ApartmentEntity result = null;
        if(apartment != null){
            ApartmentEntity apartmentEntity = new ApartmentEntity();
                    BeanUtil.beanCopy(apartment, apartmentEntity, "parent", "children", "houses","accounts");
                    result = apartmentEntity;
        }
        return result;
    }
    /*public Set<ContractEntity> getContracts() {
        Set<ContractEntity> contractSet = Sets.newHashSet();
        if(!CollectionUtils.isEmpty(this.contracts)){
            for(ContractEntity contract : this.contracts){
                ContractEntity contractEntity = new ContractEntity();
                BeanUtil.beanCopy(contract, contractEntity, "house");
                contractSet.add(contractEntity);
            }
        }
        return contractSet;
    }*/
    public Set<BedEntity> getBeds() {
        Set<BedEntity> bedSet = Sets.newHashSet();
        if(!CollectionUtils.isEmpty(this.beds)){
            for(BedEntity bed : this.beds){
                BedEntity bedEntity = new BedEntity();
                BeanUtil.beanCopy(bed, bedEntity, "house");
                bedSet.add(bedEntity);
            }
        }
        return bedSet;
    }
    /* house实体直接关联其它的表 end */

    @Override
    public String toString() {
        return "HouseEntity{" +
                "id='" + id + '\'' +
                ", code='" + code + '\'' +
                ", name=" + name +
                '}';
    }
}
